<!DOCTYPE html>
<html lang="zh">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <meta name="keywords" content="伪静态">
    <meta name="description" content="伪静态。">
    <meta name="author" content="yinq">
    <title>伪静态</title>
    <link rel="shortcut icon" type="image/x-icon" href="favicon.ico">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-touch-fullscreen" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <!-- 基础样式库 -->
    <link rel="stylesheet" type="text/css" href="{{cdn}}/static/v5/css/materialdesignicons.min.css">
    <link rel="stylesheet" type="text/css" href="{{cdn}}/static/v5/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="{{cdn}}/static/v5/css/animate.min.css">
    <link rel="stylesheet" type="text/css" href="{{cdn}}/static/v5/css/style.min.css">
    <!-- 功能插件样式 -->
    <link rel="stylesheet" href="{{cdn}}/static/v5/js/bootstrap-table/bootstrap-table.min.css">
    <link rel="stylesheet" type="text/css" href="{{cdn}}/static/v5/js/jquery-confirm/jquery-confirm.min.css">
    <!-- CodeMirror 样式 -->
    <link href="{{cdn}}/static/codemirror/lib/codemirror.css" rel="stylesheet">
    <link href="{{cdn}}/static/codemirror/addon/hint/show-hint.css" rel="stylesheet">
    <!-- CodeMirror 主题 -->
    <link href="{{cdn}}/static/codemirror/theme/monokai.css" rel="stylesheet">
    <link href="{{cdn}}/static/codemirror/theme/eclipse.css" rel="stylesheet">
    <link href="{{cdn}}/static/codemirror/theme/ambiance.css" rel="stylesheet">
    <link href="{{cdn}}/static/codemirror/theme/3024-day.css" rel="stylesheet">
    <link href="{{cdn}}/static/codemirror/theme/material.css" rel="stylesheet">
    <link href="{{cdn}}/static/codemirror/theme/dracula.css" rel="stylesheet">

</head>
<style>
    .card-body {
     height: 100vh;
   }
   .CodeMirror {
       height: 450px;
       border: 1px solid #ddd;
       border-radius: 4px;
       font-size: 14px;
       font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
   }
   .theme-selector {
       margin-bottom: 15px;
   }
   .editor-toolbar {
       display: flex;
       justify-content: space-between;
       align-items: center;
       margin-bottom: 10px;
       padding: 8px;
       background-color: #f8f9fa;
       border: 1px solid #dee2e6;
       border-radius: 4px;
   }
   .editor-info {
       font-size: 12px;
       color: #6c757d;
   }
</style>
<body>
<div class="container-fluid">

    <div class="row">

        <div class="col-lg-12">
            <div class="card">
                <header class="card-header">
                    <div class="card-title">设置伪静态</div>
                </header>
                <div class="card-body">
                    <div class="callout callout-danger mb-3">
                        <p>请选择您的应用,若设置伪静态后,网站无法正常访问,请尝试设置回 default</p>
                        <p>您可以对伪静态规则进行修改，修改完后保存即可。</p>
                        <p>规则转换工具: <a style="color:#20a53a"
                                            href="https://winginx.com/en/htaccess">Apache转Nginx</a></p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">内置规则</label>
                        <select class="form-select" onchange="GetFileBody()" id="GetRewriteList"></select>
                    </div>
                    <div class="mb-3">
                        <div class="editor-toolbar">
                            <div>
                                <label class="form-label mb-0 me-2">主题配色:</label>
                                <select id="theme-select" class="form-select form-select-sm d-inline-block w-auto" onchange="changeTheme()">
                                    <option value="monokai">Monokai (暗色)</option>
                                    <option value="eclipse">Eclipse (亮色)</option>
                                    <option value="ambiance">Ambiance (深色)</option>
                                    <option value="3024-day">3024-day (日间)</option>
                                    <option value="material">Material (现代)</option>
                                    <option value="dracula">Dracula (吸血鬼)</option>
                                </select>
                            </div>
                            <div class="editor-info">
                                语法: Nginx | 快捷键: Ctrl+Space (自动补全)
                            </div>
                        </div>
                        <label class="form-label">伪静态规则</label>
                        <textarea id="desc" class="form-control" placeholder="请输入Nginx伪静态规则..."></textarea>
                    </div>
                    <button type="button" onclick="SaveFileBody()" class="btn btn-primary me-1 btn-sm">保存</button>

                </div>
            </div>
        </div>

    </div>
</div>
</div>

<!-- 基础库 -->
<script type="text/javascript" src="{{cdn}}/static/v5/js/jquery.min.js"></script>
<script type="text/javascript" src="{{cdn}}/static/v5/js/popper.min.js"></script>
<script type="text/javascript" src="{{cdn}}/static/v5/js/bootstrap.min.js"></script>
<!-- 功能插件 -->
<script type="text/javascript" src="{{cdn}}/static/v5/js/bootstrap-notify.min.js"></script>
<script type="text/javascript" src="{{cdn}}/static/v5/js/jquery-confirm/jquery-confirm.min.js"></script>
<script type="text/javascript" src="{{cdn}}/static/v5/example/js/layer/layer.js"></script>

<!-- CodeMirror 核心文件 -->
<script src="{{cdn}}/static/codemirror/lib/codemirror.js"></script>
<!-- CodeMirror 编辑增强 -->
<script src="{{cdn}}/static/codemirror/addon/edit/closebrackets.js"></script>
<script src="{{cdn}}/static/codemirror/addon/edit/matchbrackets.js"></script>
<script src="{{cdn}}/static/codemirror/addon/selection/active-line.js"></script>
<!-- CodeMirror 自动补全功能 -->
<script src="{{cdn}}/static/codemirror/addon/hint/show-hint.js"></script>
<script src="{{cdn}}/static/codemirror/addon/hint/anyword-hint.js"></script>
<!-- CodeMirror 语言模式支持 -->
<script src="{{cdn}}/static/codemirror/mode/nginx/nginx.js"></script>
<script src="{{cdn}}/static/codemirror/mode/xml/xml.js"></script>

<script>
// CodeMirror 编辑器实例
var editor;

$(document).ready(function() {
    // 初始化伪静态规则下拉列表
    loadRewriteRules();
    
    // 初始化 CodeMirror 编辑器
    editor = CodeMirror.fromTextArea(document.getElementById('desc'), {
        lineNumbers: true,
        mode: 'nginx',
        theme: 'monokai',
        indentUnit: 4,
        lineWrapping: true,
        autoCloseBrackets: true,
        matchBrackets: true,
        styleActiveLine: true,
        showCursorWhenSelecting: true,
        extraKeys: {
            "Ctrl-Space": "autocomplete",
            "Tab": function(cm) {
                // 智能缩进
                if (cm.somethingSelected()) {
                    cm.indentSelection("add");
                } else {
                    cm.replaceSelection("    ", "end");
                }
            },
            "Shift-Tab": function(cm) {
                cm.indentSelection("subtract");
            }
        },
        hintOptions: {
            completeSingle: false,
            hint: function(cm) {
                // Nginx 关键字提示
                var cur = cm.getCursor();
                var token = cm.getTokenAt(cur);
                var start = token.start;
                var end = cur.ch;
                var word = token.string;
                
                var nginxKeywords = [
                    'location', 'rewrite', 'if', 'return', 'try_files', 'root', 'index',
                    'server_name', 'listen', 'proxy_pass', 'fastcgi_pass', 'include',
                    'error_page', 'access_log', 'error_log', 'gzip', 'expires',
                    'add_header', 'set', 'break', 'last', 'permanent', 'redirect',
                    'upstream', 'server', 'weight', 'max_fails', 'fail_timeout'
                ];
                
                var suggestions = nginxKeywords.filter(function(keyword) {
                    return keyword.indexOf(word) === 0;
                });
                
                return {
                    list: suggestions,
                    from: CodeMirror.Pos(cur.line, start),
                    to: CodeMirror.Pos(cur.line, end)
                };
            }
        }
    });
    
    // 确保编辑器内容同步
    editor.on('change', function() {
        editor.save();
    });
    
    // 设置编辑器焦点
    editor.focus();
    
    // 初始加载当前站点的伪静态规则
    loadCurrentSiteRewrite();
    
    console.log('CodeMirror 编辑器初始化完成');
});

// 加载伪静态规则列表
function loadRewriteRules() {
    $.ajax({
        url: '/GetRewriteList/',
        type: 'POST',
        success: function (data) {
            var select = document.getElementById("GetRewriteList");
            // 清空现有选项
            select.innerHTML = '';
            // 循环添加选项
            for (var i = 0; i < data.length; i++) {
                var option = document.createElement("option");
                option.value = data[i];
                option.innerHTML = data[i];
                select.appendChild(option);
            }
            // 设置默认选中第一个
            if (data.length > 0) {
                select.value = data[0];
            }
            console.log('伪静态规则列表加载完成');
        },
        error: function() {
            layer.msg('加载伪静态规则列表失败', {icon: 2});
        }
    });
}

// 加载当前站点的伪静态规则
function loadCurrentSiteRewrite() {
    $.ajax({
        url: '/GetRewriteList/GetFileBody',
        type: 'POST',
        data: {
            'path': '/'
        },
        success: function (data) {
            if (editor && data.data) {
                editor.setValue(data.data);
                editor.clearHistory();
                console.log('当前站点伪静态规则加载完成');
            }
        },
        error: function() {
            console.log('当前站点暂无伪静态规则');
        }
    });
}

// 切换主题
function changeTheme() {
    var theme = document.getElementById('theme-select').value;
    if (editor) {
        editor.setOption('theme', theme);
        console.log('主题已切换为:', theme);
    }
}

// 重写原有的 GetFileBody 函数以支持编辑器
function GetFileBody() {
    var selectedValue = document.getElementById('GetRewriteList').value;
    if (selectedValue) {
        layer.load(1, {shade: [0.1,'#fff']});
        $.ajax({
            url: '/GetRewriteList/GetFileBody',
            type: 'POST',
            data: { 'path': selectedValue },
            dataType: 'json',
            success: function(data) {
                layer.closeAll('loading');
                if (editor) {
                    editor.setValue(data.data || '');
                    editor.clearHistory();
                    editor.focus();
                } else {
                    document.getElementById('desc').value = data.data || '';
                }
                console.log('规则内容加载成功');
            },
            error: function(xhr, status, error) {
                layer.closeAll('loading');
                layer.msg('获取规则失败: ' + error, {icon: 2});
                console.error('获取规则失败:', error);
            }
        });
    }
}

// 重写原有的 SaveFileBody 函数以支持编辑器
function SaveFileBody() {
    var content = editor ? editor.getValue() : document.getElementById('desc').value;
    var selectedValue = document.getElementById('GetRewriteList').value;
    
    if (!selectedValue) {
        layer.msg('请先选择规则类型', {icon: 2});
        return;
    }
    
    if (!content.trim()) {
        layer.confirm('规则内容为空，确定要保存吗？', {
            btn: ['确定','取消']
        }, function(){
            doSave(selectedValue, content);
        });
    } else {
        doSave(selectedValue, content);
    }
}

// 执行保存操作
function doSave(selectedValue, content) {
    layer.load(1, {shade: [0.1,'#fff']});
    $.ajax({
        url: '/GetRewriteList/SaveFileBody',
        type: 'POST',
        data: {
            'data': content
        },
        dataType: 'json',
        success: function(data) {
            layer.closeAll('loading');
            if (data.status) {
                layer.msg('保存成功', {icon: 1, time: 2000});
                console.log('规则保存成功');
            } else {
                layer.msg(data.msg || '保存失败', {icon: 2});
                console.error('保存失败:', data.msg);
            }
        },
        error: function(xhr, status, error) {
            layer.closeAll('loading');
            layer.msg('保存失败: ' + error, {icon: 2});
            console.error('保存请求失败:', error);
        }
    });
}
</script>
</body>
</html>
